import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;


public class CajaDeTexto extends JTextField {

	public static final char SOLO_NUMEROS = 'A';
	public static final char SOLO_LETRAS  = 'B';
	public static final char LETRAS_Y_ESPACIOS  = 'C';
	public static final char LETRAS_Y_NUMEROS  = 'D';
	public static final char LETRAS_ESPACIOS_Y_NUMEROS  = 'E';
	public static final char CUALQUIER_CARACTER  = 'Z';
	
	private int maximaLongitud = 500;
	private int tipoCaracteresPermitidos = CUALQUIER_CARACTER;
	
	public CajaDeTexto() {
		super();
		this.addKeyListener(this.keyListener);
	}
	
	public CajaDeTexto(int maximaLongitud) {
		super();
		this.addKeyListener(this.keyListener);
		this.maximaLongitud = maximaLongitud;
	}
	
	public CajaDeTexto(char tipoCaracteresPermitidos) {
		super();
		this.addKeyListener(this.keyListener);
		this.tipoCaracteresPermitidos = tipoCaracteresPermitidos;
	}
	
	public CajaDeTexto(int maximaLongitud, char tipoCaracteresPermitidos) {
		super();
		this.addKeyListener(this.keyListener);
		this.maximaLongitud = maximaLongitud;
		this.tipoCaracteresPermitidos = tipoCaracteresPermitidos;
	}
	
	private KeyListener keyListener = new KeyListener() {
		
		@Override
		public void keyTyped(KeyEvent keyEvent) {
			validar(keyEvent);
		}
		
		@Override
		public void keyReleased(KeyEvent arg0) {

		}
		
		@Override
		public void keyPressed(KeyEvent arg0) {
			
		}
	};
	
	private void validar(KeyEvent keyEvent) {
		switch (tipoCaracteresPermitidos) {
		case SOLO_NUMEROS:
			if ((!Character.isDigit(keyEvent.getKeyChar())) ||
		    	(((JTextField)keyEvent.getSource())).getText().length() >= maximaLongitud)
		        	keyEvent.consume();
			break;
		case SOLO_LETRAS:
			if ((!Character.isLetter(keyEvent.getKeyChar())) ||
		    	(((JTextField)keyEvent.getSource())).getText().length() >= maximaLongitud)
		        	keyEvent.consume();
			break;
		case LETRAS_Y_ESPACIOS: {
			boolean a = !Character.isLetter(keyEvent.getKeyChar()) &&
						keyEvent.getKeyChar() != keyEvent.VK_SPACE;
			boolean b = (((JTextField)keyEvent.getSource())).getText().length() >= maximaLongitud; 
			if (a || b)
		        keyEvent.consume();
			}
			break;
		case LETRAS_ESPACIOS_Y_NUMEROS: {
			boolean a = !Character.isDigit(keyEvent.getKeyChar()) &&
						!Character.isLetter(keyEvent.getKeyChar()) &&
						keyEvent.getKeyChar() != keyEvent.VK_SPACE;
			boolean b = (((JTextField)keyEvent.getSource())).getText().length() >= maximaLongitud; 
			if (a || b)
		        keyEvent.consume();
			}
			break;
		case CUALQUIER_CARACTER:
			if (((JTextField)keyEvent.getSource()).getText().length() >= maximaLongitud)
		        	keyEvent.consume();
			break;
		}
	}

}
